package cn.hl.user.service.impl;

import cn.hl.basic.exception.BusinessException;
import cn.hl.basic.jwt.JwtUtils;
import cn.hl.basic.jwt.LoginData;
import cn.hl.basic.jwt.RsaUtils;
import cn.hl.basic.service.impl.BaseServiceImpl;
import cn.hl.basic.util.AjaxResult;
import cn.hl.basic.util.HttpUtil;
import cn.hl.basic.util.Md5Utils;
import cn.hl.basic.util.StrUtils;
import cn.hl.org.mapper.EmployeeMapper;
import cn.hl.system.domain.Menu;
import cn.hl.system.mapper.MenuMapper;
import cn.hl.user.constant.WxConstants;
import cn.hl.user.domain.Logininfo;
import cn.hl.user.domain.User;
import cn.hl.user.domain.Wxuser;
import cn.hl.user.dto.LoginDto;
import cn.hl.user.mapper.LogininfoMapper;
import cn.hl.user.mapper.UserMapper;
import cn.hl.user.mapper.WxuserMapper;
import cn.hl.user.service.ILogininfoService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public Map<String, Object> accountLogin(LoginDto loginDto) {
        String account = loginDto.getAccount();
        String password = loginDto.getPassword();
        Integer type = loginDto.getType();
        // 1.校验是否为空
        if (StringUtils.isEmpty(account) || StringUtils.isEmpty(password) || StringUtils.isEmpty(type)) {
            throw new BusinessException("信息不能为空!");
        }
        // 2.通过account和type去查数据库 logininfo对象
        Logininfo logininfo = logininfoMapper.accountLogin(loginDto);
        if (logininfo == null) {
            throw new BusinessException("账号或者密码错误！");
        }
        // 3.校验密码【加密加盐】
        String inputPwd = Md5Utils.encrypByMd5(loginDto.getPassword() + logininfo.getSalt());
        if (!inputPwd.equals(logininfo.getPassword())) {
            throw new BusinessException("密码错误");
        }
        // 4.状态校验 - 启用，禁用
        if(!logininfo.getDisable()){
            throw new BusinessException("你的账号被冻结，请联系管理员!!!");
        }
        // 5.将token和登录信息对象 保存在 redis 30分钟有效
        Map<String, Object> map = loginSuccessJwtHandler(logininfo);
        /*String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        // 6.将token和logininfo封装到map，并且返回
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);*/
        return map;
    }

    @Override
    public AjaxResult wechatLogin(String code) {
        // 1.准备请求和修改参数
        String url = WxConstants.GET_ACK_URL.replace("APPID", WxConstants.APPID)
                .replace("SECRET", WxConstants.SECRET)
                .replace("CODE", code);
        String jsonStr = HttpUtil.httpGet(url);
        // 2.将响应的json字符串转换为json对象
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String accessToken = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        // 3.通过openid查询wxuser对象
        Wxuser wxuser = wxuserMapper.findByOpenid(openid);
        // 4.判断wxuser是否为空
        if (wxuser != null && wxuser.getUserId() != null) {
            // 4.1绑定过，通过userId查询user对象
            User user = userMapper.findById(wxuser.getUserId());
            // 4.2根据user对象的logininfoId查询logininfo对象
            Logininfo logininfo = logininfoMapper.findById(user.getLogininfoId());
            // 4.3.将token和登录信息对象 保存在 redis 30分钟有效
            Map<String, Object> map = loginSuccessJwtHandler(logininfo);
            /*String token = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
            // 6.将token和logininfo封装到map，并且返回
            Map<String, Object> map = new HashMap<>();
            map.put("token",token);
            logininfo.setSalt(null);
            logininfo.setPassword(null);
            map.put("logininfo",logininfo);*/
            return AjaxResult.me().setResultObj(map);
        } else {
            // 4.2没有绑定，返回false，让前端跳转到绑定页面
            String params = "?accessToken=" + accessToken + "&openId=" + openid;
            return AjaxResult.me().setSuccess(false).setResultObj(params);
        }
    }

    @Override
    public AjaxResult wechatBinder(Map<String, String> map) {
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openId = map.get("openId");
        // 1.校验空值 -手机号码和手机验证码
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)) {
            throw new BusinessException("信息不能为空！");
        }
        // 2.校验手机验证码是否过期，是否正确
        Object codeObj = redisTemplate.opsForValue().get("binder:" + phone);
        if (codeObj == null) {
            throw new BusinessException("验证码已过期，请重新获取！");
        }
        if (!codeObj.toString().split(":")[0].equals(verifyCode)) {
            throw new BusinessException("验证码错误，请重新输入！");
        }
        // 3.获取wxuser对象 -发送请求 -json字符串
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        String jsonStr = HttpUtil.httpGet(url);
        Wxuser wxuser = jsonStr2Wxuser(jsonStr);
        // 4.通过phone查询user
        User user = userMapper.findByPhone(phone);
        // 5.如果为空，根据phone创建user对象 -创建logininfo对象 -保存logininfo对象 -再保存user对象
        if (user == null) {
            user = phone2User(phone);
            Logininfo logininfo = user2Logininfo(user);
            logininfoMapper.add(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.add(user);
        }
        // 6.有user对象，直接将user对象的id设置到wxuser中
        wxuser.setUserId(user.getId());
        // 7.将wxuser对象添加到数据库
        wxuserMapper.add(wxuser);
        // 8.免密登录
        Logininfo logininfo = logininfoMapper.findById(user.getLogininfoId());
        // 4.3.将token和登录信息对象 保存在 redis 30分钟有效
        Map<String, Object> result = loginSuccessJwtHandler(logininfo);
        /*String token = UUID.randomUUID().toString();
        logininfo.setPassword(null);
        logininfo.setSalt(null);
        redisTemplate.opsForValue().set(token,logininfo,30,TimeUnit.MINUTES);
        Map<String, Object> result = new HashMap<>();
        result.put("token",token);
        result.put("logininfo",logininfo);*/
        return AjaxResult.me().setResultObj(result);
    }

    private Map<String, Object> loginSuccessJwtHandler(Logininfo logininfo) {
        try {
            Map<String, Object> map = new HashMap<>();
            // 1.前台用户只需要logininfo和jwtToken
            map.put("logininfo",logininfo);
            // 2.封装loginData对象
            LoginData loginData = new LoginData();
            loginData.setLogininfo(logininfo);
            // 3.后台需要logininfo、menus、permissions、jwtToken
            if (logininfo.getType() == 0) {
                // 4.当前登录人的所有权限
                List<String> permissions = employeeMapper.findPermissionSnByLogininfoId(logininfo.getId());
                loginData.setPermissions(permissions);
                map.put("permissions",permissions);
                // 5.当前登录人的二级菜单及父级菜单
                List<Menu> menus = menuMapper.findMenuByLogininfoId(logininfo.getId());
                loginData.setMenus(menus);
                map.put("menus",menus);
            }
            // 6.对封装好的loginData对象使用工具类进行加密 -获取私钥
            PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 3000);
            // 7.将四个数据封装到map，并返回给前端
            map.put("token",jwtToken);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String pwd = StrUtils.getComplexRandomString(6);
        String md5Pwd = Md5Utils.encrypByMd5(pwd + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

    private Wxuser jsonStr2Wxuser(String jsonStr) {
        Wxuser wxuser = new Wxuser();
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        wxuser.setOpenid(jsonObject.getString("openid"));
        wxuser.setNickname(jsonObject.getString("nickname"));
        wxuser.setSex(jsonObject.getInteger("sex"));
        wxuser.setAddress(jsonObject.getString("country")
            + jsonObject.getString("province") + jsonObject.getString("city"));
        wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxuser.setUnionid(jsonObject.getString("unionid"));
        return wxuser;
    }
}
